/* ===================

AX2E (AXESCON XACML 2.0 Engine) is the Java authorization engine, which implements OASIS XACML 2.0 standard.
Copyright (C) 2007 AXESCON LLC

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA


Contact: AXESCON LLC - info{at}axescon.com

 =================== */
package axescon.xacml.engine.alg;

import axescon.xacml.api.CtxHandler;
import axescon.xacml.api.XacmlException;
import axescon.xacml.api.alg.RuleCombAlg;
import axescon.xacml.api.alg.RuleCombAlgFactory;
import axescon.xacml.engine.PolicyEvaluatorImpl;
import axescon.xacml.model.ctx.Result;
import axescon.xacml.model.ctx.XacmlCtx;
import axescon.xacml.model.policy.Rule;
import axescon.xacml.model.policy.RuleCombinerParameters;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import java.util.logging.Level;

/**
 * @author argyn
 *         Date: Jun 27, 2005
 *         Time: 11:09:19 PM
 *         Responsibilities:
 */
public class BaseRuleCombAlgFactory implements RuleCombAlgFactory {

    public RuleCombAlg getRuleCombAlg(String name) throws XacmlException {
        RuleCombAlg ret=      (RuleCombAlg) getRuleCombAlgs().get(name);
        if(ret==null)throw new XacmlException(name+" algorithm name is not supported",XacmlException.ERR_CODE_SYNTAX_UNSUPPORTED_COMB_ALG);
        return ret;

    }


    public Result combine(String name, Rule[] rules, XacmlCtx req, CtxHandler ch,
                          RuleCombinerParameters[] params, PolicyEvaluatorImpl pdp) throws XacmlException {
        return getRuleCombAlg(name).combine(rules, req, ch, params, pdp);
    }

    /**
     * Map<String, RuleCombAlg>
     */
    private Map ruleCombAlgs;

    public Map getRuleCombAlgs() {
        return ruleCombAlgs;
    }

    public void setRuleCombAlgs(Map ruleCombAlgs) {
        this.ruleCombAlgs = ruleCombAlgs;
    }

    RuleCombAlg loadClass(ClassLoader cl, String className) throws XacmlException {
        try {
            return (RuleCombAlg) (cl.loadClass(className)).newInstance();
        } catch (Exception x) {
            throw new XacmlException("BaseRuleCombAlgFactory cant load RuleCombAlg class: " + className, x
                    , XacmlException.ERR_CODE_CLASS_LOAD);
        }

    }

    public void setDefaults() throws XacmlException {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        try {
            addAlg(RuleCombAlg.DENY_OVERRIDES,
                    loadClass(cl, "axescon.xacml.engine.alg.OrderedDenyOverridesRuleAlg"));
            addAlg(RuleCombAlg.ORDERED_DENY_OVERRIDES,
                    loadClass(cl, "axescon.xacml.engine.alg.OrderedDenyOverridesRuleAlg"));
            addAlg(RuleCombAlg.ORDERED_PERMIT_OVERRIDES,
                    loadClass(cl, "axescon.xacml.engine.alg.OrderedPermitOverridesRuleAlg"));
            addAlg(RuleCombAlg.PERMIT_OVERRIDES,
                    loadClass(cl, "axescon.xacml.engine.alg.OrderedPermitOverridesRuleAlg"));
            addAlg(RuleCombAlg.FIRST_APPLICABLE,
                    loadClass(cl, "axescon.xacml.engine.alg.FirstApplicableRuleAlg"));
        } catch (Exception e) {
            // all standard classes should load
            throw new XacmlException("BaseRuleCombAlgFactory cant instatiate RuleCombAlg class", e
                    , XacmlException.ERR_CODE_CLASS_INSTANTIATE);
        }


    }

    public BaseRuleCombAlgFactory() throws XacmlException {
        this(false);
    }

    public BaseRuleCombAlgFactory(boolean isSetDefaults) throws XacmlException {
        setRuleCombAlgs(new HashMap());
        if (isSetDefaults) setDefaults();
    }

    Logger log = Logger.getLogger(BaseRuleCombAlgFactory.class.getName());

    /**
     * adds combining algorithm to the factory
     * @param urn urn of the algorithm
     * @param alg algorithm object to add
     */
    public void addAlg(String urn, RuleCombAlg alg) {

        ruleCombAlgs.put(urn, alg);
        if (log.isLoggable(Level.CONFIG)) {
            log.config("successfully added to algorithm list (urn,fn): " + urn + ", " + alg.getClass().getName());
        }
    }


    /**
     * this method validates function set
     * @throws XacmlException if syntax error is found
     */
    public void validate() throws XacmlException{

        for(int i=0;i<RuleCombAlg.MANDATORY_RULE_COMB_ALGS.length;i++){

            if(!ruleCombAlgs.containsKey(RuleCombAlg.MANDATORY_RULE_COMB_ALGS[i])){
                log.severe("Not loaded mandatory Alg urn:"+RuleCombAlg.MANDATORY_RULE_COMB_ALGS[i]);
            }

        }

    }
}
